# 字符串压缩。利用字符重复出现的次数，编写一种方法，实现基本的字符串压缩功能。
# 比如，字符串aabcccccaaa会变为a2b1c5a3。若“压缩”后的字符串没有变短，则返回原先的字符串。
# 你可以假设字符串中只包含大小写英文字母（a至z）。

# 输入："aabcccccaaa"
# 输出："a2b1c5a3"
#
# 输入："abbccd"
# 输出："abbccd"
# 解释："abbccd"压缩后为"a1b2c2d1"，比原字符串长度更长。


# https://leetcode-cn.com/problems/compress-string-lcci


# 靠直觉的第一次提交
# 执行用时 : 84 ms 击败了 31.00% 的用户
# 内存消耗 : 13.7 MB 击败了 100.00% 的用户


def compressString(S):
    if len(S) == 0:
        return S
    after = ""
    keep_i = S[0]
    count_time = 0
    for i in S:
        if i == keep_i:
            count_time += 1
            continue
        else:
            after += keep_i
            after += str(count_time)
            count_time = 1
            keep_i = i
    else:
        after += keep_i
        after += str(count_time)

    if len(after) >= len(S):
        return S
    else:
        return after


# 复盘思路
# 万物皆可双指针

def compressString_2(S):
    if len(S) == 0:
        return S
    after = ""
    length = len(S)
    i = 0
    while i < length:
        j = i
        while j < length and S[j] == S[i]:
            j += 1
        after += S[i] + str(j - i)
        i = j

    print(after)
    if len(after) >= len(S):
        return S
    else:
        return after


compressString_2("aabcccccaaa")

# 双指针这个没再提交了 看题解的记录目测是能把内存提到70%
